package com.xx.controller.xunyou.app;

import com.xx.springBootUtil.excption.BaseException;
import com.xx.springBootUtil.result.JsonResult;
import com.xx.springBootUtil.util.MessageUtil;
import com.xx.springBootUtil.validate.ValidateType;
import com.xx.springBootUtil.validate.ValidateWriteIn;
import com.xx.springBootUtil.zzcache.ZZCacheUtils;
import com.xx.util.util.RandomValidateCodeUtil;
import com.xx.xunyou.entity.item.vo.IndexVo;
import com.xx.xunyou.entity.user.XunyouUser;
import com.xx.xunyou.entity.user.vo.LoginVo;
import com.xx.xunyou.service.XunyouUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @program: xunyou-parent
 * @author: zhl
 * @create: 2019-05-04
 **/
@Api(value = "API - LoginController", description = "登录" )
@RestController
public class LoginController {

    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private XunyouUserService xunyouUserService;

    /**
     * 注册
     */
    @ApiOperation(value = "注册", notes = "注册", response = JsonResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "telephone", value = "手机号", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "string", required = true, paramType = "query"),
    })
    @ValidateWriteIn(parameter = {"userName","password"})
    @PostMapping("app/register")
    public JsonResult register(String userName, String password, String telephone, String code){
        Date date = new Date();
        XunyouUser xunyouUser = new XunyouUser();
        xunyouUser.setUserName(userName);
        xunyouUser.setUserType(2);
        xunyouUser.setTelephone(telephone);
        xunyouUser.setPassWord(MessageUtil.encodeMD5(password));
        xunyouUser.setCreateTime(date);
        xunyouUser.setUpdateTime(date);
        xunyouUserService.insert(xunyouUser);
        return new JsonResult();
    }

    /**
     * 登录
     */
    @ApiOperation(value = "登录", notes = "登录", response = LoginVo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "string", required = true, paramType = "query"),
    })
    @PostMapping("app/login")
    @ValidateWriteIn(parameter = {"userName","password"})
    public JsonResult login(String userName, String password, String code, HttpServletRequest request){

        Object attribute = request.getSession().getAttribute(RandomValidateCodeUtil.RANDOM_CODE_KEY);
        if (attribute == null) {
            throw new BaseException("验证码过期，请刷新验证码！");
        }

        if (!attribute.equals(code)) {
            throw new BaseException("验证码错误！");
        } else {
            request.getSession().removeAttribute(RandomValidateCodeUtil.RANDOM_CODE_KEY);
        }
        LoginVo loginVo = xunyouUserService.login(userName,password);
        return new JsonResult(loginVo);
    }

    /**
     * 登出
     */
    @ApiOperation(value = "登出", notes = "登出", response = JsonResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "登录凭证", dataType = "string", required = true, paramType = "query"),
    })
    @PostMapping("app/loginOut")
    @ValidateWriteIn(parameter = {"token"}, type = {ValidateType.TOKEN})
    public JsonResult loginOut(HttpServletRequest request,String token){

        ZZCacheUtils.delete(token);
        return new JsonResult();
    }

    /**
     * 获取验证码
     */
    @ApiOperation(value = "获取验证码", notes = "获取验证码", response = JsonResult.class)
    @ApiImplicitParams({
    })
    @GetMapping(value = "app/verificationCode")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }
}
